<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// | 该文件的开源协议以所在项目的LICENSE文件为准，请遵守开源协议要求
// +----------------------------------------------------------------------
// | 焦点轮播图/图集
// +----------------------------------------------------------------------
namespace app\cms\http\api;

use app\admin\attributes\auth;
use app\cms\helper\cache;
use app\cms\model\FocusModel;
use Inphp\Core\Db\PDO\Query;
use Inphp\Core\Object\Message;
use Inphp\Core\Util\Str;

class focus
{
    /**
     * 登陆账号的UID
     * @var int
     */
    public int $uid = 0;

    public function index(?array $params = null): Message
    {
        //参数
        $params = $params ?? getClient()->get;
        //优先从缓存获取
        $cache = cache::get($params, "focus");
        if ($cache) {
            //缓存中不为空时，直接返回
            return httpMessage($cache);
        }
        $id = $params["id"] ?? ($params["name"] ?? null);
        if (empty($id)) {
            return httpMessage("参数无效");
        }
        //构建查询
        $db = FocusModel::emptyQuery()->where(is_numeric($id) ? "id" : "name", $id);
        //非后台管理，仅能取得对应站点的分类数据
        $user = authUserInfo();
        $admin = $params["admin"] ?? 0;
        if ($admin != 1 || is_null($user) || $user["admin"] == 0) {
            //需要自动识别站点ID
            $siteId = $params["siteId"] ?? 0;
            $siteId = is_numeric($siteId) && $siteId > 0 ? ceil($siteId) : 0;
            if ($siteId <= 0) {
                $site = matchCMSSite();
                if (!empty($site)) {
                    $siteId = $site["id"];
                }
            }
            if ($siteId <= 0) {
                return httpMessage("未识别出站点ID");
            }
            //返回通用分类和指定站点的分类
            $db->where(function (Query $query) use($siteId) {
                $query->whereNumberInSet([$siteId, 0], "siteId")
                    ->orWhereEmpty("siteId");
            });
        }
        $item = $db->first();
        if (empty($item)) {
            return httpMessage("未找到图集");
        }
        $item["pictures"] = FocusModel::decodePictures($item["pictures"]);
        //保存到缓存
        cache::set($params, $item, "focus");
        return httpMessage($item);
    }

    /**
     * 获取列表
     * @param array|null $params
     * @return array
     */
    public function list(?array $params = null): array
    {
        //参数
        $params = $params ?? getClient()->get;
        //优先从缓存获取
        $cache = cache::get($params, "focus/list");
        if ($cache) {
            //缓存中不为空时，直接返回
            return $cache;
        }
        //构建查询
        $db = FocusModel::emptyQuery();
        //
        $user = authUserInfo();
        $admin = $params["admin"] ?? 0;
        if ($admin == 1 && !is_null($user) && $user["admin"] == 1) {
            //站点ID可以为多选
            $siteId = $params["siteId"] ?? null;
            $siteId = !empty($siteId) ? Str::trim($siteId) : null;
            if (!empty($siteId)) {
                $siteIds = explode(",", $siteId);
                $sids = [];
                foreach ($siteIds as $id) {
                    if (is_numeric($id) && $id > 0 && !in_array(ceil($id), $sids)) {
                        $sids[] = ceil($id);
                    }
                }
                if (!empty($sids)) {
                    $db->where(function (Query $q) use($sids) {
                        $q->whereNumberInSet($sids, "siteId")
                            ->orWhereEmpty("siteId");
                    });
                }
            }
            //
            $state = $params["state"] ?? 'all';
            $state = $state == 1 || $state == '0' ? $state : null;
            if (!is_null($state)) {
                $db->where("state", $state);
            }
        } else {
            //非后台获取，需要进行SITE ID处理，并且仅支持固定SITE ID
            //优先使用GET参数，再到origin，再到host
            $siteId = $params["siteId"] ?? 0;
            $siteId = is_numeric($siteId) && $siteId > 0 ? ceil($siteId) : 0;
            if ($siteId <= 0) {
                $site = matchCMSSite();
                if (!empty($site)) {
                    $siteId = $site["id"];
                }
            }
            if ($siteId == 0) {
                //未指定站点ID的时候，不返回任何数据
                return [
                    "rows"      => 0,
                    "page"      => 1,
                    "pages"     => 0,
                    "list"      => []
                ];
            }
            $db->where(function (Query $q) use($siteId) {
                $q->whereNumberInSet([$siteId, 0], "siteId")
                    ->orWhereEmpty("siteId");
            });
            //仅显示可显示的链接
            $db->where("state", 1);
        }
        //行数
        $rows = $db->rows();
        //当前页数
        $page = $params["page"] ?? 1;
        $page = is_numeric($page) && $page > 0 ? ceil($page) : 1;
        //总页数
        $pages = 1;
        //列表数据
        $list = [];
        if ($rows > 0) {
            $total = $params["total"] ?? 30;
            $total = is_numeric($total) && $total > 0 ? $total : 30;
            $total = min($total, 500);
            $pages = ceil($rows / $total);
            $page = $page > $pages ? $pages : $page;
            $offset = $total * ($page - 1);
            //排序
            $obf = $params["obf"] ?? "id";
            $obf = in_array($obf, ["time", "id"]) ? $obf : "id";
            $obt = $params["obt"] ?? "desc";
            $obt = strtolower($obt);
            $obt = $obt == "asc" ? "asc" : "desc";
            $list = $db->orderBy($obf, $obt)->get($total, $offset);
            foreach ($list as &$item)
            {
                //处理图片
                $item["pictures"] = FocusModel::decodePictures($item["pictures"]);
            }
        }
        //返回列表数据，包含行数、页码、总页数、数据列表
        $data = compact("rows", "page", "pages", "list");
        cache::set($params, $data, "focus/list");
        return $data;
    }

    /**
     * 添加、修改焦点轮播图
     * @return Message
     */
    #[auth("cms/focus")] public function save(): Message
    {
        //站点ID
        $siteId = POST("siteId");
        $siteId = !empty($siteId) ? Str::trim($siteId) : null;
        $sids = [];
        if (!empty($siteId)) {
            $sidList = explode(",", $siteId);
            foreach ($sidList as $sid) {
                if (is_numeric($sid) && ceil($sid) > 0 && !in_array(ceil($sid), $sids)) {
                    $sids[] = ceil($sid);
                }
            }
        }
        //名称
        $name = POST("name");
        $name = !empty($name) ? Str::trim($name) : null;
        if (empty($name)) {
            return httpMessage("缺少图集名称");
        }
        $name = mb_strlen($name) > 20 ? mb_substr($name, 0 , 20) : $name;
        //图片
        $pictures = POST('pictures');
        $pictures = is_array($pictures) ? $pictures : (@json_decode($pictures, true) ?? []);
        $pics = [];
        foreach ($pictures as $picture)
        {
            if(is_string($picture)){
                $picture = parseUploadFilesUrl($picture);
                $picture = is_array($picture) ? $picture[0] : $picture;
                if (empty($picture)) {
                    continue;
                }
                $picture = [
                    "picture"   => $picture,
                    "desc"      => '',
                    "url"       => ''
                ];
            }
            if(is_array($picture))
            {
                $src = $picture['picture'] ?? '';
                $src = parseUploadFilesUrl($src);
                $src = is_array($src) ? $src[0] : $src;
                if(!empty($src))
                {
                    $pics[] = [
                        "picture"   => $src,
                        "desc"      => $picture['desc'] ?? '',
                        "url"       => $picture['url'] ?? ''
                    ];
                }
            }
        }
        if (empty($pics)) {
            return httpMessage("缺少图片，至少使用一张图片作为图集");
        }
        $id = POST("id");
        $id = is_numeric($id) && $id > 0 ? ceil($id) : 0;

        $data = [
            "uid"       => $this->uid,
            "siteId"    => !empty($sids) ? join(",", $sids) : null,
            "name"      => $name,
            "pictures"  => json_encode($pics, 256)
        ];

        $db = FocusModel::emptyQuery();
        $method = "insert";
        if ($id > 0) {
            $db->where("id", $id);
            $method = "update";
        }
        if ($db->{$method}($data)) {
            //清除缓存
            cache::clean("focus");
            return httpMessage(0, "保存成功");
        }
        return httpMessage("保存失败，请稍后再试");
    }

    /**
     * 修改状态
     * @return Message
     */
    #[auth("cms/focus")] public function switch(): Message
    {
        $id = POST("id");
        $id = is_numeric($id) && $id > 0 ? ceil($id) : 0;
        if ($id <= 0) {
            return httpMessage("ID参数无效");
        }
        $db = FocusModel::emptyQuery()
            ->where("id", $id)
            ->setRaw("state", "if(`state`=1, 0, 1)");
        if ($db->update()) {
            //清除缓存
            cache::clean("focus");
            return httpMessage(0, "操作成功");
        }
        return httpMessage("操作失败");
    }

    /**
     * 修改状态
     * @return Message
     */
    #[auth("cms/focus")] public function delete(): Message
    {
        $id = POST("id");
        $id = is_numeric($id) && $id > 0 ? ceil($id) : 0;
        if ($id <= 0) {
            return httpMessage("ID参数无效");
        }
        $db = FocusModel::emptyQuery()
            ->where("id", $id);
        if ($db->delete()) {
            //清除缓存
            cache::clean("focus");
            return httpMessage(0, "已删除{$db->getAffectRows()}行数据");
        }
        return httpMessage("操作失败");
    }
}